package com.zwcloud.zw.railway.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * HttpUtils 工具类
 * - 兼容原 sendPostRequest(String url, String body, String accessToken)
 * - 推荐使用 sendPostRequest(String url, Map<String,Object> param, String accessToken) 更安全
 * - GET 请求接口保持原样
 */
@Slf4j
@Component
public class HttpUtils {

    private static final RestTemplate restTemplate = new RestTemplate();

    /**
     * 发送 POST 请求
     * 保留原接口，自动清洗 String body 中的非法字符（\n\r\t）
     * @param url 请求地址
     * @param body String 类型 JSON
     * @param accessToken token
     * @return ResponseEntity<String>
     */
    public ResponseEntity<String> sendPostRequest(String url, String body, String accessToken) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");

        // 自动清洗 body
        String cleanBody = body.replaceAll("[\\n\\r\\t]", "").trim();

        log.debug("POST URL: {}", url);
        log.debug("POST Body: {}", cleanBody);

        HttpEntity<String> entity = new HttpEntity<>(cleanBody, headers);

        return restTemplate.postForEntity(url, entity, String.class);
    }

    /**
     * 推荐用法：发送 POST 请求，传 Map，自动清洗 String 字段
     * @param url 请求地址
     * @param param 参数 Map
     * @param accessToken token
     * @return ResponseEntity<String>
     */
    @SneakyThrows
    public ResponseEntity<String> sendPostRequest(String url, Map<String, Object> param, String accessToken) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");

        // 自动清洗 param
        Map<String, Object> cleanParam = new HashMap<>();
        for (Map.Entry<String, Object> entry : param.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof String) {
                String cleanValue = ((String) value).replaceAll("[\\n\\r\\t]", "").trim();
                cleanParam.put(entry.getKey(), cleanValue);
            } else {
                cleanParam.put(entry.getKey(), value);
            }
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonBody = objectMapper.writeValueAsString(cleanParam);


        log.debug("POST URL: {}", url);
        log.debug("POST Body: {}", jsonBody);

        HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);

        return restTemplate.postForEntity(url, entity, String.class);
    }

    /**
     * 发送 GET 请求，支持 Authorization 头
     * @param url 请求地址
     * @param authToken token
     * @return ResponseEntity<String>
     */
    public ResponseEntity<String> sendGetRequest(String url, String authToken) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", "application/json");
        if (authToken != null && !authToken.isEmpty()) {
            headers.set("Authorization", authToken);
        }

        HttpEntity<Void> requestEntity = new HttpEntity<>(headers);

        log.debug("GET URL: {}", url);

        return restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
    }

    /**
     * 重载方法，不需要认证时使用
     * @param url 请求地址
     * @return ResponseEntity<String>
     */
    public ResponseEntity<String> sendGetRequest(String url) {
        return sendGetRequest(url, null);
    }

}
